import { Option, TRecord } from "@/types";
import Taro from "@tarojs/taro";
import { SetsTypeOptions, UnitOptions } from "./options";
export * from "./genNode";
export * from "./options";

// 获取日期信息
const getDateInfo = (date: Date) => {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return {
    year,
    month,
    day,
    hour,
    minute,
    second,
  };
};

// 导出一个函数，用于获取格式化日期
export const getFormatDate = (date?: Date): string => {
  if (!date) {
    date = new Date();
  }
  const { year, month, day } = getDateInfo(date);

  return `${year}-${month}-${day}`;
};

const numberTest = /^\d\.\s/;
export const getMdString = (type, value, cursor): [string, number] => {
  // const isRow =
  //   value?.slice(-2) !== "\n" && value !== "" && type !== "code_end";

  const beforeCursor = value.slice(0, cursor);
  const afterCursor = value.slice(cursor);

  const arr = beforeCursor.split("\n");
  const lastRow = arr.at(-1);

  let innerValue = "";

  if (lastRow !== "") {
    innerValue += "\n";
  }

  switch (type) {
    case "head":
      innerValue += "## ";
      break;
    case "list":
      innerValue += "- ";
      break;
    case "number": {
      if (lastRow === "") {
        innerValue += "1. ";
      } else {
        if (!numberTest.test(lastRow)) {
          innerValue += "1. ";
        } else {
          const num = Number(lastRow.split(".")[0]);
          innerValue += `${num + 1}. `;
        }
      }
      break;
    }
    case "code":
      innerValue += "```warning\n \n```";
      break;
    default:
      break;
  }

  let pos = type === "code" ? cursor + 12 : cursor + innerValue.length;
  return [beforeCursor + innerValue + afterCursor, pos];
};

// 返回选项列表的label
export const getOptionTxt = (value: number | string, options: Option[]) => {
  for (const option of options) {
    if (option.value === value) {
      return option.label;
    }
  }
  return "";
};

// 返回选项列表的index
export const getOptionIndex = (value: number | string, options: Option[]) => {
  for (const [index, option] of options.entries()) {
    if (option.value === value) {
      return index;
    }
  }
  return -1;
};

// 克隆
export function deepClone(obj, hash = new WeakMap()) {
  if (obj === null || typeof obj !== "object") return obj;
  if (hash.has(obj)) return hash.get(obj);

  let clone = Array.isArray(obj) ? [] : {};
  hash.set(obj, clone);

  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      clone[key] = deepClone(obj[key], hash);
    }
  }
  return clone;
}

// 生成唯一id
export function uniqid({
  length = 9,
  timestamp = true,
  safeRandom = false,
} = {}) {
  // 生成加密安全随机数（优先使用crypto API）
  const getRandom = () => {
    if (safeRandom && typeof crypto !== "undefined") {
      const buffer = new Uint8Array(length);
      crypto.getRandomValues(buffer);
      return Array.from(buffer, (byte) => byte.toString(36))
        .join("")
        .substr(0, length);
    }
    return Math.random().toString(36).substr(2, length);
  };
  const timePart = timestamp ? Date.now().toString(36) : "";
  const randomPart = getRandom();

  return timePart + randomPart;
}

// 获取图片地址
export const getImg = (url: string) =>
  `${process.env.IMAGE_URL}/motions/self/${url}`;

// 预览图片
export const previewImage = (url: string) => {
  const img = getImg(url);

  Taro.previewImage({
    urls: [img],
    current: img,
  });
};

const screenWidth = Taro.getSystemInfoSync().screenWidth;

// rpx 转 px 函数
export const rpxToPx = (rpx) => {
  return (rpx * screenWidth) / 750;
};

export const getSecondsFormat = (seconds: number, padding = true) => {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;

  if (padding) {
    return `${minutes.toString().padStart(2, "0")}:${remainingSeconds
      .toString()
      .padStart(2, "0")}`;
  }

  return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
};

export const getFormatRecordValue = (item: TRecord): string[] => {
  if (item.recordWay === 0) {
    const weight = getOptionTxt(item.unit, UnitOptions);
    const count = getOptionTxt(item.setsType, SetsTypeOptions);
    return item.sets.map((set) => `${set[0]}${weight}/${set[1]}${count}`);
  } else {
    return [getSecondsFormat(item.takeTime)];
  }
};
